package com.bdqn.controller;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.base.R;
import com.bdqn.pojo.GenConfig;
import com.bdqn.service.GeneratorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 代码生成器接口
 *
 * @author LILIBO
 * @since 2023-04-25
 */
@Api(tags = "代码生成器接口")
@RestController
@RequestMapping("/generator")
public class GeneratorController {

    @Resource
    private GeneratorService generatorService;

    /**
     * 分页查询数据库表
     *
     * @param tableName 参数集
     * @return 数据库表
     */
    @ApiOperation("分页查询数据库表")
    @GetMapping("/page")
    public R<IPage> list(Page page, String tableName) {
        return R.success(generatorService.queryPage(page, tableName));
    }

    /**
     * 生成代码
     */
    @ApiOperation(value = "生成代码", notes = "生成代码（请下载压缩包文件）")
    @GetMapping("/code")
    @SneakyThrows
    public void gen(@ApiParam(value = "模块名称") @RequestParam(required = false, defaultValue = "") String moduleName, @ApiParam(value = "表名") @RequestParam(required = false, defaultValue = "") String tableName, HttpServletResponse response) {
        GenConfig genConfig = new GenConfig();
        genConfig.setModule(moduleName);
        genConfig.setTableName(tableName);

        byte[] data = generatorService.generatorCode(genConfig);

        response.reset();
        response.setHeader("Content-Disposition", String.format("attachment; filename=%s.zip", genConfig.getTableName()));
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
    }

}
